import http from './request';

interface UploadResponse {
    msg: string;
    code: number;
    url: string;
}

/**
 * 通用文件上传方法
 * @param file 文件路径
 * @param params 额外参数
 * @returns Promise<string> 返回上传后的文件URL
 */
export const uploadFile = async (file: string, params = {}): Promise<string> => {
    try {
        const result = await http.upload<UploadResponse>('common/upload', {
            // #ifdef APP-PLUS || H5
            files: [{ // 需要上传的文件列表
                name: 'file',
                uri: file
            }],
            // #endif
            // #ifdef MP-WEIXIN || MP-ALIPAY
            filePath: file,
            name: 'file',
            // #endif
            formData: params,
            custom: {
                loading: false // 是否显示loading
            }
        })

        if (result.code === 200) {
            return result.url
        }
        throw new Error(result.data.msg || '上传失败')
    } catch (error: any) {
        throw new Error(error.message || '上传失败')
    }
}

/**
 * 选择并上传图片
 * @param options 选择图片的配置项
 * @param params 上传时的额外参数
 * @returns Promise<string> 返回上传后的图片URL
 */
export const chooseAndUploadImage = (options = {}, params = {}): Promise<string> => {
    return new Promise((resolve, reject) => {
        uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            ...options,
            success: async (res) => {
                try {
                    const tempFilePath = res.tempFilePaths[0]
                    const url = await uploadFile(tempFilePath, params)
                    resolve(url)
                } catch (error) {
                    reject(error)
                }
            },
            fail: (error) => {
                reject(new Error(error.errMsg || '选择图片失败'))
            }
        })
    })
} 